package jedis;

import com.alibaba.fastjson.JSONObject;
import jedis.testbean.User;
import redis.clients.jedis.Jedis;
import serializeutil.SerializeUtils;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/7/31 11:05
 * @since JDK 1.8
 */
public class JedisUtils {

    private static final String IP="localhost";

    private static final Integer PORT=6379;

    private static Jedis jedis;

    static {
        jedis=new Jedis(IP, PORT);
    }



    public static void main(String[] args) throws Exception {
       // User user=new User("张三",18,"湖南");
        //setKeyObject("user",user);
        User user=getObjectByKey("user",User.class);
        System.out.println(JSONObject.toJSON(user));
    }

    public static void setKeyStringValue(String key,String value){
        jedis.set(key,value);
    }

    public static String getStringValueByKey(String key){
        return jedis.get(key);
    }

    public static void setKeyList(String key,String[] list){
        jedis.lpush(key,list);
    }

    public static List<String> getListByKey(String key){
        return jedis.lrange(key,0,0);
    }

    /**
     * 获取所有的key
     * @return
     */
    public static Set<String> getALlKey(){
        return jedis.keys("*");
    }


    public static <T> void setKeyObject(String key,T t) throws Exception{
        byte[] bytes= SerializeUtils.serizlize(t);
        jedis.set(key.getBytes(),bytes);
    }

    public static <T> T getObjectByKey(String key,Class<T> cls) throws Exception{
        byte[] bytes=jedis.get(key.getBytes());
        return SerializeUtils.deserialize(bytes,cls);
    }

}
